package antidestiny.java2dex.ui.activity;

import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.PopupMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.kodis.ui.fragment.MainFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import antidestiny.java2dex.Jing;
import antidestiny.java2dex.R;
import antidestiny.java2dex.ui.dialog.NewFileDialogBuilder;
import antidestiny.java2dex.utils.ProjectUtils;
import antidestiny.utilib.Aide;
import antidestiny.utilib.io.FileUtils;
import antidestiny.utilib.ui.fragment.explorer.ExplorerFragment;
import antidestiny.utilib.ui.fragment.explorer.ExplorerManagerI;
import antidestiny.utilib.ui.fragment.explorer.FileItem;

public class WorkActivity extends AppCompatActivity implements ExplorerManagerI, ExplorerFragment.OnListFragmentInteractionListener {

    ExplorerFragment fileListFragment;
    FragmentManager fragmentManager;
    MainFragment workFragment;

    DrawerLayout drawer;
    /**
     * 工程候选
     */
    Spinner projectsSpinner;

    //用pro后缀的文件表示整个java工程
    private File projectFile = null;
    File workSpace;

    private View.OnTouchListener editorTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideFileManager();
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work);
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.setDisplayHomeAsUpEnabled(true);

        fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().setCustomAnimations(R.anim.in_from_left, R.anim.out_to_left).commit();
        workSpace = new File(Jing.getWorkSpace());
        FileUtils.mkDirsSafely(workSpace, true);
        fileListFragment = (ExplorerFragment) fragmentManager.findFragmentById(R.id.fragment_files);
        fileListFragment.selectMode(false);
        fileListFragment.init(workSpace, workSpace, this);
        fileListFragment.refresh();

        if (savedInstanceState == null) {
            workFragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_work);
            //恢复工作现场
            String[] filesLastTime = jieFiles(getSharedPreferences(Jing.WORK_PREFERENCES, MODE_PRIVATE).getString(Jing.PREF_OOPEN_FILES, ""));
            for (String f : filesLastTime) {
                File file = new File(f);
                if (!file.exists() || !file.isFile()) {
                    Aide.t("移除文件：" + file);
                    continue;
                }
                workFragment.addTab(f);
            }
        } else
            workFragment = (MainFragment) getSupportFragmentManager().getFragment(savedInstanceState, "workFragment");
        workFragment.setViewTouchListener(editorTouchListener);

        projectsSpinner = (Spinner) findViewById(R.id.spinner_current_project);//工程候选
        projectsSpinner.setAdapter(currentProjectSpAdapter);


        drawer = (DrawerLayout) findViewById(R.id.layout_drawer);
        if (workFragment.getFileCount() == 0) showFileManager();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerFiles();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, "workFragment", workFragment);
    }

    /**
     * 记录打开的文件
     */
    private void registerFiles() {
        String[] files = workFragment.getOpenFiles();
        SharedPreferences sharedPreferences = getSharedPreferences(Jing.WORK_PREFERENCES, MODE_PRIVATE);
        sharedPreferences.edit().putString(Jing.PREF_OOPEN_FILES, lianFiles(files)).apply();
    }

    private String lianFiles(String files[]) {
        String str = "";
        for (String file : files) {
            str += file + '\n';
        }
        return str;
    }

    private String[] jieFiles(String files) {
        return files.split("\n");
    }

    private void hideFileManager() {
        drawer.closeDrawer(findViewById(R.id.layout_filemanager));
    }

    private void showFileManager() {
        drawer.openDrawer(findViewById(R.id.layout_filemanager));
    }


    private void refreshProjectsSpinner() {
        projects.clear();
        projects.addAll(FileUtils.getAll(workSpace, ProjectUtils.ACCEPT_PRO_FILES, null));
        currentProjectSpAdapter.notifyDataSetChanged();
    }


    @Override
    public void onChooseResult(int chooseRequest, @Nullable List<FileItem> selectedFiles) {

    }

    @Override
    public void onPasteBoardChange(@Nullable File file) {
        View paste=findViewById(R.id.button_paste);
        if (file==null){
            paste.setVisibility(View.GONE);
        }else{
            paste.setVisibility(View.VISIBLE);
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_add://新建文件
                PopupMenu popMenu = new PopupMenu(this, v);
                popMenu.inflate(R.menu.workspace_new_file);
                Menu menu = popMenu.getMenu();
                if (!fileListFragment.getCurrentDir().equals(new File(Jing.getWorkSpace())))
                    menu.findItem(R.id.menu_new_project).setVisible(false);
                if (projectFile == null) {
                    menu.findItem(R.id.menu_new_java).setVisible(false);
                    menu.findItem(R.id.menu_new_class).setVisible(false);

                }
                popMenu.setOnMenuItemClickListener(popMenuListener);
                popMenu.show();
                break;
            case R.id.button_parent_folder:
                fileListFragment.back();
                break;
            case R.id.button_paste:
                fileListFragment.pasteFile();
                break;
        }
    }

    private PopupMenu.OnMenuItemClickListener popMenuListener = new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            return onOptionsItemSelected(item);
        }
    };

    /**
     * 报告文件创建结果
     */
    NewFileDialogBuilder.FileBuilderI constructReporter = new NewFileDialogBuilder.FileBuilderI() {
        @Override
        public void onFileCreated(File f) {
            if (FileUtils.suffixCompare(f, "java")) {
                workFragment.addTab(f);
                workFragment.selectTab(workFragment.getTabIndex(f));
                fileListFragment.refresh();
                hideFileManager();
            } else if (FileUtils.suffixCompare(f, "pro")) {
                projectFile = f;
                projects.add(f);
                refreshProjectsSpinner();
            }

        }
    };

    ArrayList<File> projects = new ArrayList<>();

    //工程候选适配器
    BaseAdapter currentProjectSpAdapter = new BaseAdapter() {

        @Override
        public int getCount() {
            //没有工程可选时i至少显示一个“无工程”
            return projects.size() == 0 ? 1 : projects.size();
        }

        @Override
        public Object getItem(int position) {
            if (projects == null || projects.size() == 0) return null;
            return projects.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = new TextView(WorkActivity.this);
            String fileName = "无打开的工程";
            Object item = getItem(position);
            if (item != null) {
                fileName = ((File) item).getName();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
            }
            ((TextView) convertView).setText(fileName);
            return convertView;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.work, menu);
        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (drawer.isDrawerOpen(findViewById(R.id.layout_filemanager))) {
                    hideFileManager();
                    return true;
                }
                break;
        }
        return super.onKeyUp(keyCode, event);

    }

    private void newProject() {
        NewFileDialogBuilder builder = new NewFileDialogBuilder();
        builder.setBuilderInterface(constructReporter);
        builder.newProject(this, new File(Jing.getWorkSpace())).show();
    }

    private void createFile(int menuId) {
        Aide.t("创建文件：" + menuId);
        NewFileDialogBuilder builder = new NewFileDialogBuilder();
        builder.setBuilderInterface(constructReporter);
        int type;
        switch (menuId) {
            case R.id.menu_new_class:
                type = Jing.TYPE_CLASS_FILE;
                break;
            case R.id.menu_new_java:
                type = Jing.TYPE_JAVA_FILE;
                break;
            case R.id.menu_create_common_file:
                type = Jing.TYPE_EMPTY_FILE;
                break;
            case R.id.menu_mkdir:
                type = Jing.TYPE_DIR;
                break;
            default:
                throw new TypeNotPresentException(menuId + "", new Throwable("未知的文件类型"));
        }
        builder.buildFile(this, type, fileListFragment.getCurrentDir(), projectFile).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_create_common_file:
            case R.id.menu_new_java:
            case R.id.menu_new_class:
            case R.id.menu_mkdir:
                createFile(item.getItemId());
                return true;
            case R.id.menu_new_project:
                newProject();
                return true;
            case R.id.menu_files:
                showFileManager();
                return true;
            case R.id.item_paste:
                return fileListFragment.onMenuItemClick(item);
        }
        return false;
    }

    @Override
    public boolean onListFragmentInteraction(FileItem item, View v) {
        return false;
    }

    /**
     * 文件夹管理器中的文件点击
     */
    @Override
    public boolean onFileItemClick(FileItem item, View v) {
        File file = new File(item.path);

        if (file.isFile() && (FileUtils.suffixCompare(file.getName(), "java", "xml", "txt", Jing.PROJECT_POSTFIX)))
        {
            workFragment.addTab(file.getAbsolutePath());
            workFragment.selectTab(workFragment.getTabIndex(file));
            hideFileManager();

            File pro = ProjectUtils.getProject(file);
            if (this.projectFile == null || !this.projectFile.equals(pro)) {
                this.projectFile = pro;
                refreshProjectsSpinner();
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean onFileItemLongClick(FileItem item, View v) {
        return false;
    }

    @Override
    public boolean onFileSystemChange(File file) {
        return false;
    }
}
